﻿using AutoMapper;
using BasicData.Domain;
using BasicData.ErrorCode;
using BasicData.Infastruucture;
using BasicData.Read.API.application.Command.Permission;
using BasicData.Read.API.DTO;
using MediatR;

namespace BasicData.Read.API.application.CommandHandler.Permission
{
    public class PermissionQueryTreeCommandHandler : IRequestHandler<PermissionQueryTreeCommand, ApiResult<List<PermissionDTO>>>
    {
        private readonly IBaseRepository<PermissionModel> permissionRepo;
        private readonly IMapper mapper;

        public PermissionQueryTreeCommandHandler(IBaseRepository<PermissionModel> permissionRepo, IMapper mapper)
        {
            this.permissionRepo = permissionRepo;
            this.mapper = mapper;
        }
        public Task<ApiResult<List<PermissionDTO>>> Handle(PermissionQueryTreeCommand request, CancellationToken cancellationToken)
        {
            ApiResult<List<PermissionDTO>> res = new ApiResult<List<PermissionDTO>>();
            res.Code = BaseEnums.Success;
            res.Msg = "权限树状查询成功";
            res.Data = GetTree(0);
            return Task.FromResult(res);
        }

        private List<PermissionDTO> GetTree(int ParentId)
        {
            var permission = permissionRepo.GetAll().Where(o => o.ParentId == ParentId);
            List<PermissionDTO> list = mapper.Map<List<PermissionDTO>>(permission.ToList());
            foreach (var item in list)
            {
                item.id = item.PermissionId;
                item.children = GetTree(item.id);
            }
            return list;
        }

    }
}
